<template>
    <div class="generate-image-wrapper">
        <div>
            <Form ref="form" :model="formData" :rules="rules" inline>
                <FormItem prop="imageRef">
                    <Select filterable
                        transfer-class-name="my-select"
                        v-model="formData.imageRef"
                        placeholder="镜像"
                        @on-change="changeImage"
                        style="width: 180px;"
                        transfer
                        clearable
                        filterable>
                        <Option
                            v-for="(value, key) in imageList"
                            :value="value.id"
                            :key="key"
                            :title="value.imageName">{{ value.imageName }}</Option>
                    </Select>
                </FormItem>
                <FormItem prop="flavorRef">
                    <Select filterable
                        transfer-class-name="my-select"
                        v-model="formData.flavorRef"
                        placeholder="配额"
                        @on-change="changeFlavor"
                        style="width: 180px;"
                        transfer
                        clearable
                        filterable>
                        <Option
                            v-for="(value, key) in flavorList"
                            :value="value.id"
                            :key="key"
                            :title="value.flavorName">{{ value.flavorName }}</Option>
                    </Select>
                </FormItem>
                <FormItem prop="count">
                    <InputNumber 
                        :max="100" 
                        :min="1" 
                        v-model="formData.count" 
                        placeholder="虚拟机数量" 
                        style="width: 180px;" ></InputNumber>
                </FormItem>
                <FormItem>
                    <Button type="primary" @click="addImage()">创建</Button>
                </FormItem>
            </Form>
        </div>
        <div class="image-wrapper" v-if="selectImageList.length > 0">
            <div class="image-item header flex-between">
                <span class="text-ellipsis">镜像名称</span>
                <span class="text-ellipsis">配额</span>
                <span class="text-ellipsis">虚拟机个数</span>
                <span class="text-ellipsis">操作</span>
            </div>
            <div
                v-for="(image, index) in selectImageList"
                :key="`${index}${image.imageRef}`"
                class="image-item flex-between"
            >
                <span class="text-ellipsis" :title="image.imageName">{{ image.imageName }}</span>
                <span class="text-ellipsis" :title="image.flavorName">{{ image.flavorName }}</span>
                <span class="text-ellipsis">{{ image.count }}</span>
                <span
                    class="text-ellipsis"
                    @click="delImage(index)"
                    style="color:#db4747;cursor:pointer;"
                    >删除</span
                >
            </div>
        </div>
        <Button 
            long 
            type="primary" 
            style="margin-top: 10px;"
            @click="templateAutomatic" 
            :loading='generateLoad'
            v-if="selectImageList.length > 0">生成工程模板</Button>
    </div>
</template>
<script>
import { getallImage, getallFlavor } from '@/api/question';
import { getTempInfpByID } from '@/api/proTemplate.js';
import { templateAutomatic } from '@/api/selfStudy/courseExp';
export default {
    name: 'GenerateTemplate',
    props: {
        clearBash: {
            type: Boolean,
            default: () => false
        }
    },
    data() {
        return {
            formData: { imageRef: '', flavorRef: '', count: 1 },
            rules: {
                imageRef: [
                    {
                        type: 'string',
                        required: true,
                        trigger: 'blur,change',
                        message: '镜像不能为空'
                    }
                ],
                flavorRef: [
                    {
                        type: 'string',
                        required: true,
                        trigger: 'blur,change',
                        message: '配额不能为空'
                    }
                ],
                count: [
                    { type: 'number', max: 100, min: 1, message: '输入范围：1~100', trigger: 'blur,change' },
                    { type: 'number', required: true, message: '虚拟机个数不能为空', trigger: 'blur,change' },
                ],
            },
            imageList: [],
            flavorList: [],
            selectImageList: [],
            current: {
                image: {},
                flavor: {}
            },
            generateLoad:false
        };
    },
    computed: {
        count() {
            let count = this.selectImageList.reduce((pre, cur, index) => {
                return pre + cur.count;
            }, 0);
            return count;
        }
    },
    mounted() {
        this.getAllImage();
        this.getAllFlavor();
    },
    methods: {
        resetFields() {
            this.$refs['form'].resetFields()
        },
        addImage() {
            this.$refs['form']
                .validate((valid) => {
                    if (valid) {
                        let imageName = this.current.image.imageName;
                        let flavorName = this.current.flavor.flavorName;
                        let item = Object.assign({}, this.formData, {
                            imageName,
                            flavorName
                        });
                        this.$refs['form'].resetFields();
                        this.selectImageList.push(item);
                    }
                })
                .catch((error) => {});
        },
        delImage(index) {
            this.selectImageList.splice(index, 1);
        },
        addImageList() {},
        changeImage(id) {
            if (!id) {
                return;
            }
            this.current.image = this.imageList.find((item) => item.id === id);
            this.formData.flavorRef = '';
            this.flavorList = this.flavorListCopy.filter(
                (item) =>
                    item.ram > Number(this.current.image.minRam) &&
                    item.disk > Number(this.current.image.minDisk)
            );
        },
        changeFlavor(id) {
            this.current.flavor = this.flavorListCopy.find((item) => item.id === id);
        },
        templateAutomatic() {
            let data = [];
            this.generateLoad = true
            this.selectImageList.forEach((item) => {
                let { imageRef, flavorRef } = item;
                for (let i = 0; i < item.count; i++) {
                    data.push({
                        imageRef,
                        flavorRef
                    });
                }
            });
            templateAutomatic(data).then(({ code, data, message }) => {
                if (code === 1) {
                    let templateId = data;
                    this.querytempByID(templateId);
                    this.generateLoad = false
                } else {
                    this.$Message.error(message);
                    this.generateLoad = false
                }
            });
        },
        querytempByID(id) {
            getTempInfpByID(id)
                .then((res) => {
                    if (res.data.code === 1) {
                        this.selectImageList = [];
                        // this.formData = { imageRef: '', flavorRef: '', count: 1 };
                        this.$refs['form'].resetFields();
                        this.$emit('on-success', {
                            id: id,
                            name: res.data.data.name
                        });
                    }
                })
                .catch((err) => {
                    console.log(err);
                });
        },
        getAllImage() {
            let obj = {
                nodeType: 'base'
            };
            let search = {
                pageIndex: 1,
                pageSize: 9999
            };
             if (this.clearBash) {
                delete obj.nodeType
            }
            getallImage(obj, search).then((data) => {
                if (data.code === 1) {
                    this.imageList = data.data.items.filter(item=>item.access!==false)
                }
            });
        },
        getAllFlavor() {
            const search = {
                pageIndex: 1,
                pageSize: 9999
            };
            getallFlavor(search).then((data) => {
                if (data.code === 1) {
                    let flavorList = data.data.items;
                    this.flavorList = flavorList;
                    this.flavorListCopy = flavorList;
                }
            });
        }
    }
};
</script>
<style>
.my-select,
.my-select .ivu-select-dropdown-list,
.my-select .ivu-select-item {
    width: 180px;
}

.my-select .ivu-select-item {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
</style>

<style scoped>
.image-wrapper {
    width: 100%;
}

.flex-between {
    display: flex;
    justify-content: space-around;
}

.text-ellipsis {
    width: 25%;
    text-align: center;
}

.image-item {
    border-bottom: 1px solid #e8eaec;
}

.image-item > span {
    height: 40px;
    line-height: 40px;
    font-size: 14px;
    color: #515a6e;
}

.image-item.header > span {
    background: #f8f8f9;
    font-weight: bold;
}
</style>
